<template>
  <div class="container">
    <!-- 左侧 -->
    <div class="left">
      <!-- 菜单选择组件 推荐城市模块-->
      <MenuNav />
    </div>
    <div class="right">
      <!-- 搜索模块 -->
      <div ref="searchCity">
        <SearchCity v-if="postList" />
      </div>
      <!-- 推荐攻略 -->
      <!-- 头部文字 -->
      <div class="strategy">
        <h3>推荐攻略</h3>
        <el-button type="primary" icon="el-icon-edit" @click="createStory">写游记</el-button>
      </div>
      <!-- 文章列表组件 -->
      <PostItem :articlesData="item" v-for="(item,index) in dataList" :key="index" />
      <ToTop />
      <!-- 加载提示结构 -->
      <div
        class="loading_box"
        :class="loading ? 'loading' : ''"
        v-loading="loading"
        element-loading-spinner="el-icon-loading"
        element-loading-text="拼命加载中"
      ></div>
      <!-- 没有结果的显示 -->
      <div
        v-if="postList.length == 0 && !loading"
        style="height:50px;color:#999;margin-top:20px"
      >抱歉，没找到该城市的相关攻略</div>
      <!-- 分页结构 -->
      <el-pagination
        v-if="postList.length != 0"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageIndex"
        :page-sizes="[1, 3, 5, 10]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>
  </div>
</template>

<script>
import MenuNav from '@/components/post/menuNav.vue'
import SearchCity from '@/components/post/searchCity.vue'
import PostItem from '@/components/post/postItem.vue'
import ToTop from '@/components/toTop.vue'
export default {
  components: {
    MenuNav, SearchCity, PostItem, ToTop
  },
  data() {
    return {
      postList: [],
      pageIndex: 1,
      pageSize: 3,
      total: 0,          //文章总数目
      dataList: [],      //存放当前页的文章数据         
      loading: true,       //加载提示  
    }
  },
  mounted() {  //首页搜索跳转
    if (!this.$route.query.city) {   //点击头部导航渲染全部文章
      this.getPostData()
    }
    if (this.$route.query.city) {
      this.goSearchPost()            //获取对应城市的文章数据
    }
  },
  methods: {
    // 封装 获取所有文章数据
    getPostData() {
      // 发送请求前先显示加载
      this.loading = true;
      // console.log(this.$route.query.city);
      this.$axios({
        url: '/posts',
      })
        .then(res => {
          console.log(res);
          this.postList = res.data.data
          this.total = res.data.total
          // 获取赞数前4的数据
          this.loopList = [...this.postList].sort((a, b) => { return b.like - a.like })
          this.loopList = this.loopList.splice(0, 4)
          console.log(this.loopList);
          //获取当前页
          this.getPageData()
          // 获取到数据 --关闭加载
          this.loading = false;
        })
        .catch(err => {
          console.dir(err)
          if (err.response.data.statusCode == 500) {
            this.getPostData()
          }
        })
    },
    getPageData() {
      this.dataList = this.postList.slice(this.pageSize * (this.pageIndex - 1), this.pageSize * this.pageIndex)
      // console.log(this.dataList);
    },
    // 更改每页显示记录数 
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.pageSize = val
      this.getPageData()
    },
    // 更改当前显示页
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.pageIndex = val
      // Element.scrollIntoView() 方法让当前的元素滚动到浏览器窗口的可视区域内。
      this.$refs.searchCity.scrollIntoView();
      this.getPageData()
    },
    //封装--根据城市获取数据  （监听搜索组件的 信息 优化成监听路由参数变化）
    goSearchPost() {
      this.pageIndex = 1;
      this.loading = true;
      this.$axios({
        url: '/posts',
        params: { city: this.$route.query.city }
      })
        .then(res => {
          console.log(res);
          this.postList = res.data.data
          this.total = res.data.total
          //获取当前页
          this.getPageData()
          this.loading = false;
        })
        .catch(err => {
          console.dir(err)
          if (err.response.data.statusCode == 500) {
            this.goSearchPost()
          }
        })
    },
    //写游记
    createStory() {
      // console.log(this.$store.state.user.userinfo.token);
      if (this.$store.state.user.userinfo.token) {
        this.$router.push('/post/create')
      } else {
        this.$message.warning({
          showClose: true,
          message: '未登录，请先登录'
        })
        this.$router.push('/user/login')
        this.$store.commit('user/setBackurl', location.href)
      }

    },
  },
  watch: {
    $route() {
      if (!this.$route.query.city) {   //点击头部导航渲染全部文章
        this.getPostData()
      }
      if (this.$route.query.city) {
        this.goSearchPost()            //获取对应城市的文章数据
      }
    }
  }
}
</script>

<style lang="less" scoped>
.container {
  display: flex;
  width: 1000px;
  margin: 20px auto;
  .left {
    flex: 25%;
    margin-right: 40px;
  }
  .right {
    flex: 75%;
    .strategy {
      height: 50px;
      width: 100%;
      display: flex;
      justify-content: space-between;
      align-items: center;
      border-bottom: 1px solid #ddd;
      h3 {
        font-weight: 400;
        color: #ffa500;
        height: 50px;
        line-height: 50px;
        border-bottom: 2px solid #ffa500;
        font-size: 18px;
      }
    }
  }
}
// 补充加载结构
.loading_box {
  transition: all 0.5s;

  /deep/.el-icon-loading {
    font-size: 60px;
    font-weight: 700;
    color: #ccc;
  }

  /deep/ .el-loading-text {
    font-size: 18px;
    color: #ccc;
  }
}
.loading {
  margin-top: 20px;
  height: 100px;
}
</style>